import util from './util.js';
import authLogin from './autuLogin.js';
import sdk from './sdk.js';
import CONFIG from '../config.js';

/** 上传文件地址 */
const UPLOAD_API_METHOD = 'task.biztitlearea.upload';

/**
 * 发送请求
 * path 文件路径
 * type 请求类型 4身份证
 */
export default function request(path, type, { noAuth = false, noVerify = false }) {
  if (!noAuth) {
    //登录过期自动登录
    if (!util.checkLogin()) return authLogin().then(res => { return request(path, type, { noAuth, noVerify }); });
  }
  if (CONFIG.IS_GATEWAY) {
    return gatewayRequest(path, type, noVerify);
  } else {
    return apiRequest(path, type, noVerify);
  }
} 

/** 定义方法 */
request['upload'] = (path, type, opt) => request(path, type, opt || {})

/** api请求 */
const apiRequest = function (path, type, noVerify) {
  var header = CONFIG.HEADER;
  // 添加token验证
  if (getApp().globalData.token) {
    header[CONFIG.TOKENNAME] = 'Bearer ' + getApp().globalData.token;
  }
  var url_ = CONFIG.HTTP_REQUEST_URL + '/' + UPLOAD_API_METHOD + '/';
  return new Promise((reslove, reject) => {
    wx.uploadFile({
      url: url_,
      header: header,
      filePath: path,
      name: 'file',
      formData: { type: type },
      success: (res) => {
       // return reslove(res.data, res);
        // http请求不成功
        if (res.statusCode != 200) {
          return reject(res.errMsg);
        }
        if (noVerify || !res.data.sub_code) {
          return reslove(res.data, res);
        }
        // 需要重新登陆处理
        if ([400000].indexOf(res.data.sub_code) !== -1) {
          util.logout()
          return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify }); });
        }
        reject(res.data.sub_msg);
      },
      fail: (msg) => {
        console.log(msg);
        reject('请求失败');
      }
    })
  });
}

/** 走网关请求 */
const gatewayRequest = function (path, type, noVerify) {
  var datastr = JSON.stringify({ type: type});
  var params = {
    app_id: CONFIG.GATEWAY_APPID,
    version: CONFIG.API_VERSION,
    charset: 'utf-8',
    format: 'json',
    timestamp: sdk.formatDate(new Date()),
    method: UPLOAD_API_METHOD,
    data: datastr
  }; 
  // 添加token验证
  if (getApp().globalData.token) {
    params.token = getApp().globalData.token;
  }
  params.sign = sdk.buildSign(params, CONFIG.GATEWAY_APPSECRET);
  return new Promise((reslove, reject) => {
    wx.uploadFile({
      url: CONFIG.GATEWAY_REQUEST_URL,
      header: CONFIG.HEADER,
      filePath: path,
      name: 'file',
      formData: params,
      success: (res) => {
        // http请求不成功
        if (res.statusCode != 200) {
          return reject(res.errMsg);
        }
        var data_ = JSON.parse(res.data) || {};
        var response_ = data_.response;
        // 业务请求成功
        if (noVerify || response_.code == '10000') {
          return reslove(response_.data, res);
        }
        // 需要登陆处理
        if ([400000].indexOf(response_.code) !== -1) {
          util.logout()
          return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify }); });
        }
        if (response_.data) {
          reject(response_.data.sub_msg);
        } else {
          reject(response_.msg);
        }
      },
      fail: (msg) => {
        console.log(msg);
        reject('请求失败');
      }
    })
  });
}

